/**
 * TODO:文件描述
 *
 * @title register
 * @projectName grpc-demo
 * @author vivi
 * @date 2024/4/14 15:21
 */

package server

import (
	"context"
	"fmt"
	"time"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/sd"
	"github.com/go-kit/kit/sd/etcdv3"
	"os"
)

func RegisterEtcd(etcdHost, etcdPort, svcHost, svcPort string, logger log.Logger) (registrar sd.Registrar) {

	// etcd的地址
	etcdServerAddr := []string{fmt.Sprintf("%s:%s", etcdHost, etcdPort)}

	// 服务的名称和端口
	serviceName := "my-service"

	ttl := 5 * time.Second
	options := etcdv3.ClientOptions{
		DialTimeout:   ttl,
		DialKeepAlive: ttl,
	}

	// 创建etcd客户端
	etcdClient, err := etcdv3.NewClient(context.Background(), etcdServerAddr, options)
	if err != nil {
		fmt.Printf("Failed to create etcd client: %v", err)
		os.Exit(1)
	}

	// 创建一个etcd实例
	registrar = etcdv3.NewRegistrar(etcdClient, etcdv3.Service{
		Key:   serviceName,                                        // 设置etcd中的键值
		Value: fmt.Sprintf("%s:%s", svcHost, svcPort),             // 设置etcd中的值，即服务的地址和端口
		TTL:   etcdv3.NewTTLOption(10*time.Second, 5*time.Second), // 设置TTL
	}, logger)

	return registrar
}
